<template>
  <div>
    <home-header :city=city></home-header>
    <home-swiper :swiperList=swiperList></home-swiper>
    <home-icon :iconList=iconList></home-icon>
    <home-recommend :recommendList=recommendList></home-recommend>
    <home-weekend :weekendList=weekendList></home-weekend>
  </div>
</template>

<script>
import HomeHeader from './components/Header'
import HomeSwiper from './components/Swiper'
import HomeIcon from './components/Icon'
import HomeRecommend from './components/Recommend'
import HomeWeekend from './components/Weekend'
import { mapState } from 'vuex'
import BMap from 'BMap'
export default {
  name: 'home',
  components: {
    HomeHeader,
    HomeSwiper,
    HomeIcon,
    HomeRecommend,
    HomeWeekend
  },
  data () {
    return {
      iconList: [],
      recommendList: [],
      weekendList: [],
      swiperList: [],
      lastCity: ''
    }
  },
  computed: {
    ...mapState(['city'])
  },
  methods: {
    getHomeInfo () {
      console.log(111 + this.city)
      this.$http.get('/api/home.json?city=' + this.city).then(res => {
        const data = res.data
        if (data.ret) {
          this.swiperList = data.data.swiperList
          this.iconList = data.data.iconList
          this.recommendList = data.data.recommendList
          this.weekendList = data.data.weekendList
        }
      })
    },
    getUserLocaltion () {
      let myCity = new BMap.LocalCity()
      myCity.get(result => {
        let cityName = result.name
        let currentCity = cityName.substr(0, cityName.length - 1)
        if (!localStorage.city) {
          this.$store.state.city = currentCity
          localStorage.city = currentCity
        } else {
          this.$store.state.city = localStorage.city
        }
        this.getHomeInfo()
      })
    }
  },
  mounted () {
    // 编译好的html挂载到页面完成后执行，一般执行ajax请求，整个实例只执行一次
    this.getUserLocaltion()
    this.lastCity = this.city
  },
  activated () {
    if (this.lastCity !== this.city) {
      this.lastCity = this.city
      this.getHomeInfo()
    }
  }
}
</script>
